package com.cqie.secondhandtransaction.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.secondhandtransaction.DTO.UserDTO;
import com.cqie.secondhandtransaction.DTO.UserDetailsDTO;
import com.cqie.secondhandtransaction.controller.params.LoginParam;
import com.cqie.secondhandtransaction.controller.params.RegisterParam;
import com.cqie.secondhandtransaction.entity.UserInfo;
import com.cqie.secondhandtransaction.exception.BusinessException;
import com.cqie.secondhandtransaction.exception.IllegalParameterException;
import com.cqie.secondhandtransaction.mapper.UserInfoMapper;
import com.cqie.secondhandtransaction.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.secondhandtransaction.service.file.AliYunService;
import com.cqie.secondhandtransaction.utils.DateUtil;
import com.cqie.secondhandtransaction.config.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-10
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AliYunService aliYunService;

    /**
     * 登录
     */
    @Override
    public UserDetailsDTO login(LoginParam param) {
        String username = param.getUsername();
        String password = param.getPassword();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            if (authentication.isAuthenticated()) {
                UserDetailsDTO userDetails = (UserDetailsDTO) authentication.getPrincipal();
                if (!Objects.equals(userDetails.getUsername(), username)) {
                    throw new BadCredentialsException("账户或密码错误！");
                }
                //创建登录令牌
                String token = JwtUtil.createToken(username, userDetails.getAuthorities().toString(), password);
                userDetails.setToken("Bearer " + token);
                userDetails.setPassword(null);
                return userDetails;
            } else {
                throw new BadCredentialsException("密码错误！");
            }
        } catch (Exception e) {
            throw new BadCredentialsException(e.getMessage());
        }
    }

    /**
     * 注册
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterParam param, MultipartFile picture) {
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUserName, param.getUserName()));
        if (Objects.nonNull(userInfo)) {
            throw new IllegalParameterException("用户名已存在！");
        }
        userInfo = new UserInfo();
        userInfo.setUserName(param.getUserName());
        userInfo.setPassword(passwordEncoder.encode(param.getPassword()));
        userInfo.setPhone(param.getPhone());
        userInfo.setAddress(param.getAddress());
        userInfo.buildRole();

        //设置头像
        buildPicture(picture, userInfo);
        userInfoMapper.insert(userInfo);
    }

    /**
     * 修改用户信息
     *
     * @param userInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(UserDTO userInfo, MultipartFile picture) {
        UserInfo info = userInfoMapper.selectById(userInfo.getId());
        if (Objects.nonNull(info)) {
            info.setUserName(userInfo.getUserName());
            info.setPhone(userInfo.getPhone());
            info.setAddress(userInfo.getAddress());
            info.setUpdateTime(DateUtil.getNowDate());
            if(Objects.nonNull(info.getPicture())){
                aliYunService.deleteFilesByUrl(Collections.singletonList(info.getPicture()));
            }
            //设置头像
            buildPicture(picture, info);
        }
        userInfoMapper.updateById(info);
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserInfo(Long id) {
        UserInfo info = userInfoMapper.selectById(id);
        if (Objects.isNull(info)) {
            throw new IllegalParameterException("用户不存在！");
        }
        aliYunService.deleteFilesByUrl(Collections.singletonList(info.getPicture()));
        userInfoMapper.deleteById(id);
    }

    private void buildPicture(MultipartFile picture, UserInfo userInfo) {
        if (Objects.nonNull(picture) && !picture.isEmpty()) {
            List<String> list;
            try {
                list = aliYunService.uploadFiles(Collections.singletonList(picture));
            } catch (IOException e) {
                throw new BusinessException("图像上传失败！");
            }
            userInfo.setPicture(CollectionUtils.isEmpty(list) ? "" : String.join(",", list));
        }
    }


}
